﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FlexFlow
{
    /// <summary>
    /// 函数构建器
    /// </summary>
    internal class FunctionBuilder
    {

        private StringBuilder funcSb = new StringBuilder();
        private int funcIndex;
        /// <summary>
        /// 判断指定字符串是否为函数定义
        /// </summary>
        /// <param name="val">
        /// 字符串
        /// </param>
        /// <returns>
        /// 一个值，表示该字符串是否为函数定义
        /// </returns>
        /// <remarks>
        /// 有效的函数定义字符串结构为%{...}%，其中...为函数体
        /// </remarks>
        public bool IsFunc(string val)
        {
            int codeStart = val.IndexOf("%{");
            int codeEnd = val.IndexOf("}%");
            return (codeStart >= 0 && codeStart < codeEnd);
        }
        /// <summary>
        /// 通过函数定义构造函数实体
        /// </summary>
        /// <param name="val">
        /// 函数定义文本
        /// </param>
        /// <returns>
        /// 转换后的函数
        /// </returns>
        /// <remarks>
        /// 输入的函数定义字符串结构为%{...}%其中...为函数体，通过该函数转换后，将会
        /// 以private void f*(){...}的形式返回，用于参与cshtml页面的构造。
        /// </remarks>
        /// <example>
        /// 输入 %{TextBox("测试文本框","默认值");}%，
        /// 输出 private void f1(){TextBox("测试文本框","默认值");}
        /// </example>
        public string BuildFunc(string val)
        {
            int codeStart = val.IndexOf("%{");
            int codeEnd = val.IndexOf("}%");
            if (codeStart >= 0 && codeStart < codeEnd)
            {
                string funcContent = val.Substring(codeStart + 2, codeEnd - codeStart - 2);
                string funcNewName = "f" + ++funcIndex + "()";
                string res = val.Replace(funcContent, funcNewName + ";");
                funcContent = funcContent.Replace("“", "\"").Replace("”", "\"");
                funcSb.AppendLine("private void " + funcNewName + "{" + funcContent + "}");
                return res;
            }
            else
            {
                return val;
            }
        }

        public FunctionBuilder()
        {
            funcSb.AppendLine("@functions{");
        }
        /// <summary>
        /// 停止构建函数并返回函数文本
        /// </summary>
        /// <returns>
        /// 构建的函数文本
        /// </returns>
        /// <remarks>
        /// 本函数会在表单编译引擎生成cshtml时调用，返回@functions{
        /// private void f1(){...}
        /// private void f2(){...}
        /// }
        /// 这样的字符串
        /// </remarks>
        public string EndBuild()
        {
            funcSb.AppendLine("}");
            string s = funcSb.ToString();
            return funcSb.ToString();
        }
    }
}
